package org.xiaoai.cp;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/***
 * 生产数据
 * @author book
 *
 */
public class Producer<T> implements Runnable {

	/**
	 * 存放数据的队列
	 */
	private BlockingQueue<T> queue;
	/**
	 * 控制线程
	 */
    private volatile boolean  isRunning = true;
    
    
    private static AtomicInteger count = new AtomicInteger();
	
    /**
     * 线程随机休息时间
     */
    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;
   
	public Producer(BlockingQueue<T> queue) {
		this.queue = queue;
	}



	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		T data = null;
		while(isRunning){
		   System.out.println("==========：开始生产数据");
		   try {
			Thread.sleep(DEFAULT_RANGE_FOR_SLEEP);
			data = (T) (count.incrementAndGet() + "数据产生了");
			System.out.println("=========:"+data);
			if(!queue.offer(data, 2, TimeUnit.SECONDS)){
				System.out.println("生产数据失败了");
			}
			
		} catch (InterruptedException e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
		}finally{
			System.out.println("生产数据结束了........");
		}
			
		}
	}

	
	
	public void stop(){
		isRunning = false;
	}
}
